<template>
    <div>
        <el-form label-width="80px" :model="SPUInfo">
            <el-form-item label="SPU名称">
                <el-input placeholder="SPU名称" v-model="SPUInfo.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select placeholder="请选择品牌" v-model="SPUInfo.tmId">
                    <el-option v-for="(tm, index) in tradeMarkList" :key="tm.id" :label="tm.tmName"
                        :value="tm.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" :rows="3" placeholder="请输入SPU的描述信息" v-model="SPUInfo.description">
                </el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="spuImageList"
                    :on-success="handlerSuccess">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                    <el-option v-for="(unselect, index) in unSelectSaleAttr" :key="unselect.id" :label="unselect.name"
                        :value="`${unselect.id}:${unselect.name}`"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName"
                    @click="AddSaleAttr">添加销售属性</el-button>
            </el-form-item>

            <el-form-item>
                <el-table style="width: 100%;" border :data="SPUInfo.spuSaleAttrList">
                    <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
                    <el-table-column prop="saleAttrName" label="属性名" width="width"></el-table-column>
                    <el-table-column prop="prop" label="属性值名称列表" width="width">
                        <template slot-scope="{ row, $index }">

                            <el-tag closable :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList"
                                style="margin: 0px 5px;" @close="row.spuSaleAttrValueList.splice(index, 1)">{{
            tag.saleAttrValueName }} </el-tag>

                            <el-input v-if="row.inputVisible" :ref="`inputValue${$index}`" class="input-new-tag"
                                v-model="row.inputValue" size="small" @blur="handleInputConfirm(row)"></el-input>
                            <el-button v-else class="button-new-tag" size="small"
                                @click="addSaleAttrValue(row, $index)">添加</el-button>

                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="width">
                        <template slot-scope="{ row, $index }">
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                @click="deletesaleAttr($index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: "SPUForm",
    data() {
        return {
            dialogImageUrl: '',  //照片墙
            dialogVisible: false,  //照片墙
            SPUInfo: {
                //三级分类的id
                category3Id: 0,
                //描述
                description: "",
                //spu名称
                spuName: "",
                //平台的id
                tmId: "",
                //收集SPU图片的信息
                spuImageList: [
                    // {
                    //   id: 0,
                    //   imgName: "string",
                    //   imgUrl: "string",
                    //   spuId: 0,
                    // },
                ],
                //平台属性与属性值收集
                spuSaleAttrList: [
                    // {
                    //   baseSaleAttrId: 0,
                    //   id: 0,
                    //   saleAttrName: "",
                    //   spuId: 0,
                    //   spuSaleAttrValueList: [
                    //     {
                    //       baseSaleAttrId: 0,
                    //       id: 0,
                    //       isChecked: "string",
                    //       saleAttrName: "string",
                    //       saleAttrValueName: "string",
                    //       spuId: 0,
                    //     },
                    //   ],
                    // },
                ],
            },
            tradeMarkList: [], //品牌下拉
            saleAttrList: [],  //属性下拉
            spuImageList: [],  //图片列表
            attrIdAndAttrName: '' // 选择要添加的销售属性

        }
    },
    computed: {
        unSelectSaleAttr() {
            return this.saleAttrList.filter((item) => {
                //every数组的方法，会返回一个布尔值【真，假的】
                return this.SPUInfo.spuSaleAttrList.every((item1) => {
                    return item.name != item1.saleAttrName;
                });
            });
        },

    },
    methods: {
        //照片墙删除
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        //照片墙查看
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //照片上传成功后回调
        handlerSuccess(res, file, fileList) {
            this.spuImageList = fileList;
        },
        //取消修改或添加
        cancel() {           
             //清理数据
            //Object.assign:es6中新增的方法可以合并对象
            //组件实例this._data,可以操作data当中响应式数据
            //this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
            Object.assign(this._data, this.$options.data()); 
            this.$emit("changeScene", { scene: 0, flag: "" });          
        },
        async initData(val) {
            if (val.id) {
                const spuResult = await this.$API.spu.reqSpu(val.id);
                if (spuResult.code == 200) {
                    //在修改spu的时候,需要向服务器发请求的，把服务器返回的数据（对象），赋值给spu属性
                    this.SPUInfo = spuResult.data;
                }

                const spuImageResult = await this.$API.spu.reqSpuImageList(val.id);
                if (spuImageResult.code == 200) {
                    let listArr = spuImageResult.data;
                    //由于照片墙显示图片的数据需要数组，数组里面的元素需要有name与url字段
                    //需要把服务器返回的数据进行修改
                    listArr.forEach((item) => {
                        item.name = item.imgName;
                        item.url = item.imgUrl;
                    });
                    //把整理好的数据赋值给
                    this.spuImageList = listArr;
                }
            }
            if(Number.isInteger(val)){
                this.SPUInfo.category3Id=val;
            }
            
            //品牌信息
            const tradeMarkResult = await this.$API.spu.reqTradeMarkList();
            if (tradeMarkResult.code == 200) {
                this.tradeMarkList = tradeMarkResult.data;
            }
            //获取平台全部的销售属性
            const saleResult = await this.$API.spu.reqBaseSaleAttrList();
            if (saleResult.code == 200) {
                this.saleAttrList = saleResult.data;
            }
        },
        //添加销售属性
        AddSaleAttr() {
            const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
            this.SPUInfo.spuSaleAttrList.push({ baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [], });
            this.attrIdAndAttrName = '';
        },

        //删除销售属性
        deletesaleAttr(index) {
            this.SPUInfo.spuSaleAttrList.splice(index, 1);
        },
        //添加按钮回调添加销售属性值
        addSaleAttrValue(row, index) {
            this.$set(row, "inputVisible", true);
            this.$set(row, "inputValue", "");
            this.$nextTick(() => {
                this.$refs[`inputValue${index}`].focus(); //获取焦点
            });
        },
        //属性值添加后处理
        handleInputConfirm(row) {
            const { baseSaleAttrId, inputValue } = row;
            if (inputValue.trim() == "") {
                this.$message("属性值不能为空");
                return;
            }
            //属性值不能重复,some 有一条相同就返回true
            let result = row.spuSaleAttrValueList.some(
                (item) => item.saleAttrValueName == inputValue
            );
            if (result) return;
            let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
            row.spuSaleAttrValueList.push(newSaleAttrValue);
            row.inputVisible = false;
        },
        //添加或进行保存
        async addOrUpdateSpu() {
            //整理参数：需要整理照片墙的数据
            //携带参数：对于图片，需要携带imageName与imageUrl字段
            this.SPUInfo.spuImageList = this.spuImageList.map((item) => {
                return {
                    imageName: item.name,
                    imageUrl: (item.response && item.response.data) || item.url,
                };
            });
            let result = await this.$API.spu.reqAddOrUpdateSpu(this.SPUInfo);
            if(result.code==200){
                this.$message({ type: "success", message: "保存成功" });
                 //通知父组件回到场景0
                this.$emit("changeScene", {
                scene: 0,
                flag: this.SPUInfo.id ? "修改" : "添加",
                });
            }
        },
    },

};
</script>

<style lang="scss" scoped></style>
